<template>
  <div class="raceRank">
    <div class="r-body" v-if="!isShowDetail">
      <n-spin :show="showSpin" style="--n-opacity-spinning: 0">
        <el-table size="small" class="table" :data="rankList.records" :cell-style="cellStyle">
          <el-table-column prop="rank" label="排名" align="center" width="70px">
            <template #default="scoped">
              <div v-if="scoped.row.rank !== -1 && !scoped.row.award">
                {{ scoped.row.rank }}
              </div>
              <div v-if="scoped.row.rank === -1">*</div>
              <div v-if="scoped.row.award !== null && scoped.row.award">
                <el-tooltip class="box-item" effect="dark" :content="awardContent(scoped.row)" placement="top">
                  <div class="award" :style="{ background: awardColor(scoped.row) }">
                    <i class="iconfont icon-medal"> </i>
                    <div class="rank">
                      {{ scoped.row.rank }}
                    </div>
                  </div>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="displayId" label="用户" width="300px" align="center" class="isStar">
            <template #default="scoped">
              <div class="user">
                <div class="avatar">
                  <n-badge :offset="avatarOffset" value="Star" size="small" color="#ffc10a"
                    :show="scoped.row.rank === -1">
                    <el-avatar v-if="
                      scoped.row.avatar === null || scoped.row.avatar === ''
                    ">{{ scoped.row.username[0] }}</el-avatar>
                    <n-avatar round size="large" :src="$getAvatarUrl(scoped.row.avatar)" v-else />
                  </n-badge>
                </div>
                <div>
                  <div class="id">
                    {{ scoped.row.username }}
                  </div>
                  <div>
                    {{ scoped.row.school }}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="realName" label="真实姓名" align="center" v-if="rankName === 'realname'"></el-table-column>
          <el-table-column prop="nickname" label="昵称" align="center" v-if="rankName === 'nickname'"></el-table-column>
          <el-table-column prop="totalScore" label="总ac数" align="center" width="85px">
            <template #default="scoped">
              <div class="t-all">
                <div class="totalAc">{{ scoped.row.acTotal }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="totalScore" label="总时间" align="center" width="85px">
            <template #default="scoped">
              <div class="t-all">
                <div class="totalTime">{{ scoped.row.totalTime }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-for="(item, index) in problem" prop="totalScore" align="center">
            <template #header>
              <div class="problem" @click="toProblem(item)">
                <i :style="{ color: item.color }" class="iconfont icon-icon_qiqiu2"></i>
                {{ item.displayId }}
              </div>
              <div v-if="problemAc[item.pid]">
                <el-tooltip class="box-item" effect="dark" placement="top">
                  <template #content>
                    <div class="t-title">
                      {{ problem[index].displayId }}.{{
                        problem[index].displayTitle
                      }}
                    </div>
                    <div class="accept">
                      Accepted:&nbsp;{{ problemAc[item.pid].ac }}
                    </div>
                    <div class="reject">
                      Rejected:&nbsp;
                      {{
                        parseInt(problemAc[item.pid].submitCount) -
                        parseInt(problemAc[item.pid].ac)
                      }}
                    </div>
                  </template>
                  <div class="ac">
                    ({{ problemAc[item.pid].ac }}/{{
                      problemAc[item.pid].submitCount
                    }})
                  </div>
                </el-tooltip>
              </div>
            </template>
            <template #default="scoped">
              <div class="problemScore" v-if="scoped.row.submissionInfo[item.pid] !== undefined">
                <div class="ac" @click="toStatus(scoped.row.submitIdInfo[item.pid])"
                  v-if="scoped.row.submitIdInfo[item.pid] !== undefined">
                  +{{ scoped.row.submissionInfo[item.pid] }}
                </div>
                <div class="unAc" v-else>
                  -{{ scoped.row.submissionInfo[item.pid] }}
                </div>
                <div class="time" v-if="scoped.row.submitIdInfo[item.pid] !== undefined">
                  {{ scoped.row.timeInfo[item.pid] }}
                </div>
              </div>
              <div class="problemScore" v-else>--------</div>
            </template>
          </el-table-column>
        </el-table>
      </n-spin>
    </div>
    <div class="r-foot" v-if="!isShowDetail">
      <el-pagination class="pagination" :page-sizes="[20, 50, 99]" background small layout="prev, pager, next,sizes"
        :page-count="Number(rankList.total)" v-model:current-page="rankParams.pageNum"
        v-model:page-size="rankParams.pageSize" />
    </div>
  </div>
</template>

<script setup>
import {
  onMounted,
  ref,
  defineProps,
  toRefs,
  defineExpose,
  watch,
  defineEmits,
} from "vue";
import useStore from "@/store";
import { useRoute, useRouter } from "vue-router";
import {
  getRaceRankAPI,
  getRaceProblemAPI,
  getRaceProblemAcAPI,
  getRaceProblemScoreAPI,
} from "@/api/ojAPI/ojAPI.js";
import {
  getRaceRankAdminAPI
} from "@/api/adminAPI/adminAPI.js"
import { debounce } from "@/utils/global.js";

const props = defineProps({
  rankName: {
    type: String,
    default: "",
  },
  showStar: {
    type: Boolean,
    default: false,
  },
  showAuto: {
    type: Boolean,
    default: false,
  },
  rankParams: {
    type: Object,
    default: {
      pageSize: 20,
      pageNum: 1,
      searchValue: "",
    },
  },
  awardConfig: {
    type: Array,
    default: [],
  },
  location: {
    tyep: Boolean,
    default: false,
  },
  lockRank: {
    tyep: Boolean,
    default: true,
  }
});
const { rankName, showStar, showAuto, rankParams, awardConfig, location, lockRank } =
  toRefs(props);
onMounted(() => {
  getRaceRank();
  getRaceProblem();
});
const deboundTime = ref(null);
const route = useRoute();
const router = useRouter();
const rankList = ref({
  records: [],
  total: 0,
});
const isShowDetail = ref(false);
const currentSubmitId = ref(false);
const problem = ref([]);
const avatarOffset = [-67, 20];
const problemAc = ref({});
const problemScore = ref({});
const showSpin = ref(true);
const emit = defineEmits();
const cellStyle = (data) => {
  if (data.row.rank === -1) {
    return {
      background: "#ffffcc",
    };
  }
};
const awardContent = (row) => {
  let name = "";
  for (let i = 0; i < awardConfig.value.length; i++) {
    if (parseInt(awardConfig.value[i].level) === row.award) {
      name = awardConfig.value[i].name;
    }
  }
  return name;
};
const awardColor = (row) => {
  let color = "";
  for (let i = 0; i < awardConfig.value.length; i++) {
    if (parseInt(awardConfig.value[i].level) === row.award) {
      color = awardConfig.value[i].backColor;
    }
  }
  return color;
};
const toProblem = (data) => {
  if (location.value) {
    router.push(
      `/home/racePage/${route.params.rid}/problem/${data.pid}?proId=${data.id}`
    );
  }
};
const toStatus = (data) => {
  if (location.value) {
    router.push(
      `/home/racePage/${route.params.rid}/evaluation/${data}`
    );
  }
};
const getRaceRank = () => {
  if (deboundTime.value) {
    clearTimeout(deboundTime.value);
  }
  deboundTime.value = setTimeout(async () => {
    const removeStar = showStar.value ? 1 : 0;
    const data = {
      pageSize: rankParams.value.pageSize,
      pageNum: rankParams.value.pageNum,
      removeStar: removeStar,
      cid: route.params.rid,
      keyword: rankParams.value.searchValue,
    };
    if (lockRank.value) {
      await getRaceRankAPI(data).then((res) => {
        if (res.data.code === 200) {
          rankList.value = res.data.data;
          showSpin.value = false;
        }
      });
    } else {
      await getRaceRankAdminAPI(data).then((res) => {
        if (res.data.code === 200) {
          rankList.value = res.data.data;
          showSpin.value = false;
        }
      });
    }
  });
};
const getRaceProblem = debounce(async () => {
  await getRaceProblemAPI(route.params.rid)
    .then((res) => {
      if (res.data.code === 200) {
        problem.value = res.data.data;
        getRaceProblemAc();
        getRaceProblemScore();
      }
    })
    .catch((err) => {
      console.log(err);
    });
}, 100);
const getRaceProblemAc = debounce(async () => {
  let data = [];
  problem.value.forEach((item) => {
    data.push(item.pid);
  });
  await getRaceProblemAcAPI(route.params.rid, data).then((res) => {
    if (res.data.code === 200) {
      problemAc.value = res.data.data;
    }
  });
}, 100);
const getRaceProblemScore = debounce(async () => {
  let data = [];
  problem.value.forEach((item) => {
    data.push(item.pid);
  });
  await getRaceProblemScoreAPI(route.params.rid, data).then((res) => {
    if (res.data.code === 200) {
      problemScore.value = res.data.data;
    }
  });
}, 100);
defineExpose({ getRaceRank, getRaceProblem });
</script>

<style lang="less" scoped>
.raceRank {
  width: 100%;

  .r-body {
    margin-top: 10px;

    .table {
      height: 65vh;

      .totalAc {
        font-size: 12px;
        color: #515152d8;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .totalTime {
        font-size: 12px;
        color: #515152d8;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .award {
        width: 35px;
        height: 35px;
        display: flex;
        margin-left: 6px;
        color: #fff;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;

        .rank {
          font-size: 10px;
        }

        .iconfont {
          font-size: 13px;
        }
      }

      .user {
        display: flex;
        align-items: center;
        justify-content: left;

        .avatar {
          display: flex;
          align-items: center;
          margin-right: 10px;
          margin-left: 80px;
        }

        .id {
          display: flex;
          align-items: center;
        }
      }

      .time {
        font-size: 10px;
        color: #68696a99;
        height: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .problem {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        cursor: pointer;

        .iconfont {
          font-size: 12px;
          font-weight: 550;
        }
      }

      .problem:hover {
        color: #18a058;
      }

      .ac {
        font-size: 10px;
      }

      .zero {
        color: rgba(228, 31, 31, 0.83);
        font-weight: 550;
      }

      .part {
        color: #0c61c9a1;
      }

      .full {
        color: #18a058 !important;
      }

      .problemScore {
        font-weight: 600;

        .ac {
          color: rgb(47, 255, 78);
          font-size: 14px;
          cursor: pointer;
        }

        .ac:hover {
          text-decoration: underline;
        }

        .unAc {
          color: #d18b19;
          font-size: 16px;
        }
      }
    }

    .isStar {
      background-color: #ffffcc;
    }
  }

  .r-foot {
    margin: 0 auto;
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }

}

::v-deep(.el-table td:first-child) {
  border-left: 1px solid #e2ecfa;
  border-radius: 10px 0 0 10px;
  padding: 2px;
  background: #fff;
}

::v-deep(.el-table td:last-child) {
  border-right: 1px solid #e2ecfa;
  border-radius: 0 10px 10px 0;
  padding: 2px;
  background: #fff;
}
</style>
